package com.example.baselibrary.base

import android.app.Activity
import android.content.res.Configuration
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.viewbinding.ViewBinding
import com.example.baselibrary.R
import com.gyf.immersionbar.ImmersionBar
import com.yechaoa.yutilskt.ToastUtil
import me.jessyan.autosize.AutoSizeConfig
import me.jessyan.autosize.onAdaptListener
import me.jessyan.autosize.utils.ScreenUtils


abstract class BaseActivity<VB : ViewBinding> : AppCompatActivity() {


    protected open lateinit var mBinding: VB
    var savedInstanceState: Bundle? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setH()
        this.savedInstanceState = savedInstanceState
        mBinding = getViewBinding()
        setContentView(mBinding.root)
        ImmersionBar.with(this)
            .transparentStatusBar()
            .fullScreen(true)
            .statusBarDarkFont(statusBarDark())
            .keyboardEnable(true)
            .navigationBarColor(R.color.white).init()
        initialize()
    }

    private fun setH() {
        //屏幕适配监听器
        AutoSizeConfig.getInstance().onAdaptListener = object : onAdaptListener {
            override fun onAdaptBefore(target: Any, activity: Activity) {
                //使用以下代码, 可以解决横竖屏切换时的屏幕适配问题
                //首先设置最新的屏幕尺寸，ScreenUtils.getScreenSize(activity) 的参数一定要不要传 Application !!!
                AutoSizeConfig.getInstance().screenWidth = ScreenUtils.getScreenSize(activity)[0]
                AutoSizeConfig.getInstance().screenHeight = ScreenUtils.getScreenSize(activity)[1]
                //根据屏幕方向，设置设计尺寸
                if (activity.resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) {
                    //设置横屏设计尺寸
                    AutoSizeConfig.getInstance()
                        .setDesignWidthInDp(812).designHeightInDp = 375
                } else {
                    //设置竖屏设计尺寸
                    AutoSizeConfig.getInstance()
                        .setDesignWidthInDp(375).designHeightInDp = 800
                }
            }

            override fun onAdaptAfter(target: Any, activity: Activity) {}
        }
    }

    /**
     * 状态栏字体深色或亮色
     *
     *
     * isDarkFont true 深色
     */
    protected open fun statusBarDark(): Boolean {
        return true
    }

    abstract fun getViewBinding(): VB

    /**
     * 命名与子类要区分，否则会先调用BaseActivity中同名方法，再调用BaseVmActivity中同名方法，可能会出现调用顺序导致的错误
     */
    open fun initialize() {}

    override fun onDestroy() {
        super.onDestroy()
        ToastUtil.release()
    }
}